package com.example.cgpsys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cgpsys.other.config.SystemFileConfig;
import com.example.cgpsys.beans.Result;
import com.example.cgpsys.beans.User;
import com.example.cgpsys.dao.UserDao;
import com.example.cgpsys.other.utils.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@RequestMapping("/user")
@RestController
public class UserController {

    private final UserDao userDao;

    public UserController(UserDao userDao) {
        this.userDao = userDao;
    }

    @GetMapping("/infoById")
    public Result getUserInfoById(Integer id){
        return Result.success(userDao.selectById(id));
    }

    @PutMapping("/updateInfo")
    public Result updateInfo(@RequestBody User user){
        userDao.updateById(user);
        return Result.success();
    }

    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam("avatarFile") MultipartFile avatarFile, @RequestParam("id") Integer id) throws IOException {
        if (!avatarFile.isEmpty()){
            String uploadPath = FileUtils.uploadImage(SystemFileConfig.getFileUploadPath(), avatarFile);
            if ("#".equals(uploadPath)){
                return Result.error("图片类型错误");
            }
            User user = new User();
            user.setId(id);
            user.setAvatar(uploadPath);
            userDao.updateById(user);
            return Result.success().put("imgUrl",uploadPath);
        }else{
            return Result.error("传输失败");
        }
    }

    @GetMapping("/getUserList")
    public Result loadUserList(){
        return Result.success(userDao.selectList(null));
    }

    @PostMapping("/login")
    public Result login(@RequestBody User loginUser){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginUser.getUsername());
        User user = userDao.selectOne(queryWrapper);
        if (user==null || !user.getPassword().equals(loginUser.getPassword())){
            return Result.error("用户名或密码错误");
        }
        HashMap<String,Object> result=new HashMap<>(2);
        result.put("type",user.getType());
        result.put("id",user.getId());
        return Result.success(result);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User regisUser){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",regisUser.getUsername());
        User user = userDao.selectOne(queryWrapper);;
        if (user!=null){
            return Result.error("用户名已存在");
        }
        userDao.insert(regisUser);
        return Result.success();
    }

    @GetMapping("/delete")
    public Result removeUserById(Integer id){
        userDao.deleteById(id);
        return Result.success();
    }
}
